// hooks/useRouteMeta.ts
import {useLocation} from 'react-router-dom';
import {dynamicRouter} from '@/router';
import {RouteConfig} from '@/types/router'
import {useState, useEffect, useCallback} from 'react';

const useCustomMatches = () => {
    const location = useLocation();
    const currentPath = location.pathname;

    const [matchedRoute, setMatchedRoute] = useState<any>([]);
    const [crumbList, setCrumbList] = useState<any[]>([])

    // 递归查找匹配的路由
    const findRouteFun = useCallback((routers: RouteConfig[], path: string): any => {
        for (const route of routers) {
            if (path.includes(route.path!)) {
                if (route.children) {
                    route.children = findRouteFun(route.children, path);
                    return route;
                }
                return route
            }
        }
        return null;
    }, []);

    useEffect(() => {
        let findRoute = findRouteFun(JSON.parse(JSON.stringify(dynamicRouter[0].children)), currentPath);
        setMatchedRoute({...findRoute})
    }, [currentPath, findRouteFun])

    useEffect(() => {
        if (matchedRoute) {
            const crumbList = []
            matchedRoute?.meta?.title && crumbList.push({
                title: matchedRoute.meta?.title,
                icon: matchedRoute.meta?.icon
            })
            matchedRoute.children?.meta?.title && crumbList.push({
                title: matchedRoute.children?.meta?.title,
                icon: matchedRoute.children?.meta?.icon
            })
            setCrumbList([...crumbList])
        }
    }, [matchedRoute])


    return {matchedRoute, crumbList}
};

export default useCustomMatches
